package com.zatech.cgnci.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.enums.ApprovalConfigEnum;
import com.zatech.cgnci.project.base.enums.BusinessScenariosEnum;
import com.zatech.cgnci.project.base.enums.OperationTypeEnum;
import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.base.utils.DateUtils;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.dto.*;
import com.zatech.cgnci.project.entity.CgnciApprovalInfoDO;
import com.zatech.cgnci.project.entity.CgnciBusinessInsuranceDO;
import com.zatech.cgnci.project.entity.UserEntity;
import com.zatech.cgnci.project.mapper.CgnciApprovalInfoMapper;
import com.zatech.cgnci.project.service.*;
import com.zatech.cgnci.project.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 承保管理--保单表 前端控制器
 * </p>
 *
 * @author Generator
 * @since 2024-12-20
 */
@RestController
@RequestMapping("/api/business/divide-in")
@RequiredArgsConstructor
@Api(produces = "application/json", tags = "承保管理--预约临分分入合约分入管理api接口文档")
public class CgnciBusinessDivideInController {

    private final CgnciBusinessInsuranceService cgnciBusinessInsuranceService;

    private final IApprovalService approvalService;

    private final CgnciApprovalInfoMapper approvalInfoMapper;

    private final CgnciDirectInsuranceRiskService cgnciDirectInsuranceRiskService;

    private final CgnciDirectInsuranceDetailService cgnciDirectInsuranceDetailService;

    private final CgnciReinsuranceRiskService cgnciReinsuranceRiskService;

    private final CgnciReinsuranceRiskInsuredService cgnciReinsuranceRiskInsuredService;

    private final CgnciOperationLogsService cgnciOperationLogsService;

    private final CgnciRiskService cgnciRiskService;


    @PostMapping("/page")
    @ApiOperation(value = "分页列表查询")
    public IPage<CgnciBusinessInsurancePageVO> page(@RequestBody CgnciBusinessInsuranceQueryDTO queryDTO) {
        queryDTO.setBusinessType("2");
        return cgnciBusinessInsuranceService.pageBusinessInsurance(queryDTO);
    }

    @GetMapping("/detail")
    @ApiOperation(value = "详情")
    public CgnciBusinessInsuranceMainVO detail(@RequestParam(value = "insuranceId") @NotNull(message = "insuranceId不能为空") Long insuranceId) {
        return cgnciBusinessInsuranceService.detail(insuranceId, "2");
    }

    @PostMapping("/next/create")
    @ApiOperation(value = "新增录入分入合约-下一步")
    @Transactional(rollbackFor = Exception.class)
    public Long nextCreate(@RequestBody @Valid CgnciBusinessDivideInNextCreateDTO addCreateDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();

        CgnciBusinessInsuranceDO cgnciBusinessInsuranceDO = cgnciBusinessInsuranceService.nextDivideInCreate(addCreateDTO);

        // 创建任务,绑定工作流formId. 并且关联工作台的跳转地址url以及参数
        ApprovalInfoVO approvalInfoVO = approvalService.create(FlowTaskCreateDTO.builder().approvalConfigGroupId(ApprovalConfigEnum.APPROVAL_CONFIG_009.getGroupId()).formId(String.valueOf(cgnciBusinessInsuranceDO.getInsuranceId())).formNo(cgnciBusinessInsuranceDO.getFormNo())
                .redirectionUrl(ApprovalConfigEnum.APPROVAL_CONFIG_009.getRedirectionUrl()).redirectionParam(String.valueOf(cgnciBusinessInsuranceDO.getInsuranceId())).redirectionDesc(ApprovalConfigEnum.APPROVAL_CONFIG_009.getRedirectionDesc()).build());
        cgnciOperationLogsService.insertOperationLogs(
                String.valueOf(cgnciBusinessInsuranceDO.getInsuranceId()),
                BusinessScenariosEnum.POLICY.getCode(),
                OperationTypeEnum.SUBMIT_REINSURANCE.getCode(),
                "预约临分/合约分入录入任务号：" + approvalInfoVO.getTaskId(),
                user.getNameAndCode()
        );
        return cgnciBusinessInsuranceDO.getInsuranceId();
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "新增或者修改")
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(@RequestBody @Valid CgnciBusinessInsuranceSaveOrUpdateDTO updateDTO) {
        CgnciBusinessInsuranceDO businessInsurance = cgnciBusinessInsuranceService.saveOrUpdateBusinessInsurance(updateDTO, "2");

        // 维护业务名称到工作台
        CgnciApprovalInfoDO approvalInfoDO = approvalInfoMapper.selectOne(new LambdaQueryWrapper<CgnciApprovalInfoDO>()
                .eq(CgnciApprovalInfoDO::getFormId, updateDTO.getBusinessInsuranceUpdateDTO().getInsuranceId()));
        if (VerifyUtils.isEmpty(approvalInfoDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "任务流程不存在");
        }
        approvalInfoDO.setBusinessName(updateDTO.getBusinessInsuranceUpdateDTO().getBusinessName());
        approvalInfoMapper.updateById(approvalInfoDO);

        // 提交审核
        if (VerifyUtils.isNotEmpty(updateDTO.getFlowTaskType()) && "submit".equals(updateDTO.getFlowTaskType())) {
            // 是否触发倒签
            String groupId = null;
            if (businessInsurance.getCreateTime().after(DateUtils.getTimeByType(updateDTO.getBusinessInsuranceUpdateDTO().getStartDate(), "start"))) {
                groupId = ApprovalConfigEnum.APPROVAL_CONFIG_010.getGroupId();
            }
            if (VerifyUtils.isNotEmpty(groupId)) {
                approvalInfoMapper.updateById(CgnciApprovalInfoDO.builder().approvalInfoId(updateDTO.getApprovalInfoId()).approvalConfigGroupId(groupId).build());
            }
            cgnciBusinessInsuranceService.submit(FlowTaskSubmitDTO.builder().approvalInfoId(updateDTO.getApprovalInfoId()).formId(String.valueOf(businessInsurance.getInsuranceId())).build());
        }
    }

    @PostMapping("/approve")
    @ApiOperation(value = "审核流程任务")
    @Transactional(rollbackFor = Exception.class)
    public void approve(@RequestBody @Valid FlowTaskApprovalDTO flowTaskDTO) {
        cgnciBusinessInsuranceService.approve(flowTaskDTO);
    }

    @GetMapping("/listBackNode")
    @ApiOperation(value = "获取退回流程节点")
    public List<ApprovalConfigVO> listBackNode(@RequestParam(value = "insuranceId") @NotNull(message = "insuranceId不能为空") Long insuranceId) {
        CgnciBusinessInsuranceDO businessInsuranceDO = cgnciBusinessInsuranceService.getById(insuranceId);
        return approvalService.listBackNode(String.valueOf(businessInsuranceDO.getInsuranceId()), businessInsuranceDO.getFormNo());
    }

    @PostMapping("/back")
    @ApiOperation(value = "退回流程任务")
    @Transactional(rollbackFor = Exception.class)
    public void back(@RequestBody @Valid FlowTaskBackDTO flowTaskDTO) {
        cgnciBusinessInsuranceService.back(flowTaskDTO);
    }

    @GetMapping("/signOut")
    @ApiOperation(value = "注销")
    @Transactional(rollbackFor = Exception.class)
    public void signOut(@RequestParam(value = "insuranceId") @NotNull(message = "insuranceId不能为空") Long insuranceId) {
        cgnciBusinessInsuranceService.signOut(insuranceId);
    }

    @GetMapping("/log")
    @ApiOperation(value = "获取操作日志")
    public List<ApprovalRecordVO> log(@RequestParam(value = "insuranceId") @NotNull(message = "insuranceId不能为空") Long insuranceId) {
        return cgnciBusinessInsuranceService.log(insuranceId);
    }

    @GetMapping("/insuranceRisk/deleteById")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "删除直保险种")
    public void deleteInsuranceRiskById(@RequestParam(value = "riskId") Long riskId) {
        cgnciDirectInsuranceRiskService.deleteInsuranceRisk(riskId, "2");
    }

    @GetMapping("/insuranceRisk/deleteByIds")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "批量删除直保险种")
    public void deleteInsuranceRiskByIds(@RequestParam(value = "riskIds") String riskIds) {
        List<Long> idList = Arrays.stream(riskIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        idList.forEach(id -> cgnciDirectInsuranceRiskService.deleteInsuranceRisk(id, "2"));
    }

    @GetMapping("/insuranceDetail/deleteById")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "删除直保标的明细")
    public void deleteInsuranceDetailById(@RequestParam(value = "detailId") Long detailId) {
        cgnciDirectInsuranceDetailService.deleteInsuranceDetail(detailId, "2");
    }

    @GetMapping("/insuranceDetail/deleteByIds")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "批量删除直保标的明细")
    public void deleteInsuranceDetailByIds(@RequestParam(value = "detailIds") String detailIds) {
        List<Long> idList = Arrays.stream(detailIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        idList.forEach(id -> cgnciDirectInsuranceDetailService.deleteInsuranceDetail(id, "2"));
    }

    @GetMapping("/reinsuranceRisk/deleteById")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "删除分入分出险种")
    public void deleteReinsuranceRiskDetailById(@RequestParam(value = "reinsuranceRiskId") @ApiParam(value = "reinsuranceRiskId") Long reinsuranceRiskId,
                                                @RequestParam(value = "type") @ApiParam(value = "删除模块(1-分入险种,2-分出险种,3-分入方案/再保人险种)") String type) {
        cgnciReinsuranceRiskService.deleteReinsuranceRiskForBusiness(reinsuranceRiskId, type);
    }

    @GetMapping("/reinsuranceRisk/deleteByIds")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "批量删除分入分出险种")
    public void deleteReinsuranceRiskDetailByIds(@RequestParam(value = "reinsuranceRiskIds") @ApiParam(value = "reinsuranceRiskIds") String reinsuranceRiskIds,
                                                 @RequestParam(value = "type") @ApiParam(value = "删除模块(1-分入险种,2-分出险种,3-分入方案/再保人险种)") String type) {
        List<Long> idList = Arrays.stream(reinsuranceRiskIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        idList.forEach(id -> cgnciReinsuranceRiskService.deleteReinsuranceRiskForBusiness(id, type));
    }

    @GetMapping("/reinsuranceRiskInsured/deleteById")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "删除分入分出险种标的")
    public void deleteReinsuranceRiskInsuredById(@RequestParam(value = "riskInsuredId") @ApiParam(value = "riskInsuredId") Long riskInsuredId,
                                                 @RequestParam(value = "type") @ApiParam(value = "删除模块(1-分入险种,2-分出险种,3-分入方案/再保人险种)") String type) {
        cgnciReinsuranceRiskInsuredService.deleteReinsuranceRiskInsuredForBusiness(riskInsuredId, type);
    }

    @GetMapping("/reinsuranceRiskInsured/deleteByIds")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "批量删除分入分出险种标的")
    public void deleteReinsuranceRiskInsuredByIds(@RequestParam(value = "riskInsuredIds") @ApiParam(value = "riskInsuredIds") String riskInsuredIds,
                                                  @RequestParam(value = "type") @ApiParam(value = "删除模块(1-分入险种,2-分出险种,3-分入方案/再保人险种)") String type) {
        List<Long> idList = Arrays.stream(riskInsuredIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        idList.forEach(id -> cgnciReinsuranceRiskInsuredService.deleteReinsuranceRiskInsuredForBusiness(id, type));
    }

}

